#include "dbtablemodel.h"
//#include "tablestorage.h"
#include "defines.h"
#include "abstractcontainer.h"

#include <QDebug>

DbTableModel::DbTableModel(QObject *parent, AbstractContainer *container) :
    QAbstractTableModel(parent),
    m_tables(container)
{
    m_columnsName <<tr("TableName")<<tr("Description");
}

int DbTableModel::rowCount(const QModelIndex &/*parent*/) const
{
    if(m_tables)
    {
        return m_tables->size();
    }
    else
        return 0;
}

int DbTableModel::columnCount(const QModelIndex &/*parent*/) const
{
    return m_columnsName.size();
}

QVariant DbTableModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid())
        return QVariant();
    if(role == Qt::TextAlignmentRole)
    {
        return int(Qt::AlignRight | Qt::AlignVCenter);
    }
    else if (role == Qt::DisplayRole || role == Qt::EditRole)
    {
        QString s;
        switch (index.column())
        {
        case 0: // TableName
            s = m_tables->at(index.row())->property(PROP_TABLENAME).toString();
            break;
        case 1:
            s = m_tables->at(index.row())->property(PROP_TABLEDESCIPTION).toString();
            break;
        }
        return s;
    }
    return QVariant();
}

bool DbTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if( index.isValid() && role == Qt::EditRole )
    {
        switch (index.column())
        {
        case 0: // TableName
            m_tables->at(index.row())->setProperty(PROP_TABLENAME,value);
            break;
        case 1:
            m_tables->at(index.row())->setProperty(PROP_TABLEDESCIPTION,value);
            break;
        }
        emit dataChanged(index,index);
        return true;
    }
    return false;
}

QVariant DbTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(role == Qt::DisplayRole && orientation == Qt::Horizontal)
    {
        return m_columnsName[section];
    }
    else if(role == Qt::DisplayRole && orientation == Qt::Vertical)
    {
        return QVariant(section+1);
    }
    return QVariant();
}

Qt::ItemFlags DbTableModel::flags ( const QModelIndex & index ) const
{
    Qt::ItemFlags flags = QAbstractItemModel::flags(index);
    flags |= Qt::ItemIsEditable;
    return flags;
}

void DbTableModel::setTablesList(AbstractContainer * tables)
{
    this->m_tables = tables;
    this->reset();
}

bool DbTableModel::insertRow(int row, const QModelIndex &parent)
{
    bool res = true;
    beginInsertRows(parent,row,row);
    m_tables->appendStorage(XML_TABLE);
    endInsertRows();
    return res;
}

bool DbTableModel::removeRow(int row, const QModelIndex &parent)
{
    bool res = true;
    beginRemoveRows(parent, row, row);
    m_tables->removeAt(row);
    endRemoveRows();
    return res;
}
